#!/bin/bash
# data_box_3_v0 生产版本轴承监控系统启动脚本

echo "=== 轴承监控系统生产版本启动 ==="
echo "版本: data_box_3_v0"
echo "启动时间: $(date)"
echo "当前目录: $(pwd)"
echo ""

# 激活虚拟环境
if [ -d "production_env" ]; then
    echo "🐍 激活Python虚拟环境..."
    source production_env/bin/activate
    echo "虚拟环境已激活: $(which python)"
else
    echo "❌ 未找到虚拟环境，请先运行: python3 -m venv production_env"
    exit 1
fi

# 检查必要的硬件模块
echo ""
echo "🔍 检查硬件模块..."

# 检查温度传感器模块
if [ -f "temp_GY906.py" ]; then
    echo "✅ 温度传感器模块: temp_GY906.py"
else
    echo "❌ 缺少温度传感器模块: temp_GY906.py"
fi

# 检查IMU模块
if [ -f "imu_node.py" ]; then
    echo "✅ 振动传感器模块: imu_node.py" 
else
    echo "❌ 缺少振动传感器模块: imu_node.py"
fi

# 检查录音模块
if [ -f "rec.py" ]; then
    echo "✅ 录音模块: rec.py"
else
    echo "❌ 缺少录音模块: rec.py"
fi

# 检查拍照模块
if [ -f "photo.py" ]; then
    echo "✅ 拍照模块: photo.py"
else
    echo "❌ 缺少拍照模块: photo.py"
fi

echo ""

# 检查Python包
echo "📦 检查关键Python依赖包..."
critical_packages=("flask" "flask_socketio" "numpy")
missing_packages=0

for package in "${critical_packages[@]}"; do
    if python -c "import ${package//-/_}" 2>/dev/null; then
        echo "✅ $package"
    else
        echo "❌ $package (缺失)"
        ((missing_packages++))
    fi
done

if [ $missing_packages -gt 0 ]; then
    echo "⚠️  检测到 $missing_packages 个关键包缺失"
    echo "正在安装缺失的包..."
    pip install flask flask-socketio numpy matplotlib opencv-python
fi

echo ""

# 检查设备
echo "🎥 检查摄像头设备..."
if ls /dev/video* 1> /dev/null 2>&1; then
    video_count=$(ls /dev/video* | wc -l)
    echo "✅ 检测到 $video_count 个摄像头设备"
else
    echo "❌ 未检测到摄像头设备"
fi

echo ""

# 检查I2C设备 (温度传感器)
echo "🌡️  检查I2C设备..."
if command -v i2cdetect >/dev/null 2>&1; then
    echo "扫描I2C总线1..."
    i2cdetect -y 1 2>/dev/null | grep -q "5a" && echo "✅ 检测到温度传感器(0x5A)" || echo "⚠️  未检测到温度传感器"
else
    echo "⚠️  i2c-tools未安装，无法检测I2C设备"
fi

echo ""

# 创建必要目录
echo "📁 创建数据目录..."
mkdir -p recordings test_photos logs test_data
echo "数据目录创建完成"

echo ""

# 检查端口占用
echo "🔌 检查端口5006占用情况..."
if netstat -tuln | grep :5006 >/dev/null 2>&1; then
    echo "⚠️  端口5006已被占用，正在清理..."
    pkill -f "web_bearing_monitor"
    sleep 2
else
    echo "✅ 端口5006可用"
fi

echo ""

# 启动系统
echo "🚀 启动轴承监控系统..."
echo "访问地址: http://192.168.1.5:5006"
echo "按 Ctrl+C 停止系统"
echo ""

# 设置环境变量
export PYTHONPATH="$PYTHONPATH:$(pwd)"
export FLASK_ENV=production

# 启动主程序
python web_bearing_monitor_production.py

echo ""
echo "系统已停止"
echo "停止时间: $(date)"